package org.cc.cstc.querystrategy.impl;

import com.intellij.openapi.util.text.StringUtil;
import org.cc.cstc.enums.FieldType;
import org.cc.cstc.querystrategy.QueryStrategy;
import org.cc.cstc.utils.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlQueryStrategy implements QueryStrategy {

    private final String insertSqlRegex = "INSERT\\s+INTO\\s+`?(\\w+)`?\\s*\\(([^)]+)\\)\\s*(?:VALUES|ON DUPLICATE KEY UPDATE)";
    private final Pattern insertSqlPattern = Pattern.compile(insertSqlRegex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    @Override
    public List<String> queryField(String str) {
        List<String> result = new ArrayList<>();
        Matcher matcher = insertSqlPattern.matcher(str);
        if(matcher.find()) {
            String fieldsPart = matcher.group(2);
            String[] fields = fieldsPart.split(",");
            for(String field : fields) {
                String cleanField = field.trim().replace("`", "").replace("\"", "");
                result.add(createFieldDeclaration(cleanField));
            }
        }
        return result;
    }

    /**
     * 返回完整字段
     * @param fieldName 字段名
     * @return 字符串
     */
    private String createFieldDeclaration(String fieldName) {
        FieldType fieldType = getFieldType(fieldName);
        String javaType = fieldType.getJavaType();
        if(fieldType == FieldType.STRING || fieldType == FieldType.NUMBER){
            return String.format("private %s %s;",javaType,StringUtils.isSnakeCase(fieldName) ? StringUtils.snakeCaseToCamelCase(fieldName) : fieldName);
        }else{
            return String.format("private %s %s;", javaType, StringUtils.isSnakeCase(fieldName) ? StringUtils.snakeCaseToCamelCase(fieldName) : fieldName);
        }
    }

    /**
     * 获取字段的类型
     * @param fieldName 字段名称
     * @return 类型
     */
    private FieldType getFieldType(String fieldName) {
        if (StringUtil.containsIgnoreCase(fieldName, "time") || StringUtil.containsIgnoreCase(fieldName, "date")) {
            return FieldType.DATE;
        } else if (StringUtil.containsIgnoreCase(fieldName, "number") ) {
            return FieldType.NUMBER;
        } else {
            return FieldType.STRING;
        }
    }
}
